<template>
  <div class="create-bill-container">
    <div class="page-header">
      <el-button @click="goBack" circle size="large" class="back-btn">
        <el-icon><ArrowLeft /></el-icon>
      </el-button>
      <h1>{{ isEditMode ? '✏️ 编辑账单' : '📝 记一笔' }}</h1>
      <div style="width: 40px;"></div>
    </div>

    <el-form :model="billForm" :rules="billRules" ref="billFormRef" label-position="top" class="bill-form">
      <!-- 金额输入 -->
      <el-form-item prop="amount" class="form-item-amount">
        <template #label>
          <div class="form-label">
            <span class="label-icon">💰</span>
            <span class="label-text">金额</span>
          </div>
        </template>
        <el-input
          v-model="billForm.amount"
          placeholder="请输入金额"
          type="number"
          step="0.01"
          size="large"
          class="amount-input">
          <template #prefix>¥</template>
        </el-input>
        <div v-if="needApproval" class="approval-tip">
          <el-icon><Warning /></el-icon>
          <span>金额超过100元，需要对方审批</span>
        </div>
      </el-form-item>

      <!-- 用途说明 -->
      <el-form-item prop="purpose" class="form-item-purpose">
        <template #label>
          <div class="form-label">
            <span class="label-icon">📋</span>
            <span class="label-text">用途说明</span>
          </div>
        </template>
        <el-input
          v-model="billForm.purpose"
          placeholder="请输入用途说明，如：晚餐"
          size="large"
          maxlength="100"
          show-word-limit />
      </el-form-item>

      <!-- 分类选择 -->
      <el-form-item prop="category" class="form-item-category">
        <template #label>
          <div class="form-label">
            <span class="label-icon">🏷️</span>
            <span class="label-text">分类</span>
          </div>
        </template>
        <div class="category-grid">
          <div
            v-for="cat in categories"
            :key="cat.value"
            :class="['category-item', { active: billForm.category === cat.value }]"
            @click="billForm.category = cat.value">
            <span class="category-icon">{{ cat.icon }}</span>
            <span class="category-label">{{ cat.label }}</span>
          </div>
        </div>
      </el-form-item>

      <!-- 账单日期 -->
      <el-form-item prop="billDate" class="form-item-date">
        <template #label>
          <div class="form-label">
            <span class="label-icon">📅</span>
            <span class="label-text">账单日期</span>
          </div>
        </template>
        <el-date-picker
          v-model="billForm.billDate"
          type="date"
          placeholder="选择日期"
          size="large"
          style="width: 100%"
          :disabled-date="disabledDate"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD" />
      </el-form-item>

      <!-- 截图上传 -->
      <el-form-item class="form-item-upload">
        <template #label>
          <div class="form-label">
            <span class="label-icon">📷</span>
            <span class="label-text">截图</span>
            <span class="label-optional">（选填）</span>
          </div>
        </template>
        <div class="upload-section">
          <el-upload
            :action="uploadAction"
            :headers="uploadHeaders"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            :file-list="fileList"
            list-type="picture-card"
            :limit="5"
            accept="image/*">
            <el-icon class="upload-icon"><Plus /></el-icon>
            <template #tip>
              <div class="upload-tip">最多上传5张图片，每张不超过10MB</div>
            </template>
          </el-upload>
        </div>
      </el-form-item>

      <!-- 提交按钮 -->
      <el-form-item class="form-item-submit">
        <el-button
          type="primary"
          size="large"
          @click="submitBill"
          :loading="loading"
          class="submit-btn">
          {{ isEditMode ? '💾 保存修改' : (needApproval ? '📤 提交审批' : '✅ 立即记账') }}
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Plus, Warning } from '@element-plus/icons-vue'
import { createBill, updateBill, getBillDetail } from '@/api'

const router = useRouter()
const route = useRoute()

// 分类选项
const categories = [
  { value: '餐饮', label: '餐饮', icon: '🍔' },
  { value: '购物', label: '购物', icon: '🛍️' },
  { value: '交通', label: '交通', icon: '🚗' },
  { value: '娱乐', label: '娱乐', icon: '🎮' },
  { value: '医疗', label: '医疗', icon: '💊' },
  { value: '教育', label: '教育', icon: '📚' },
  { value: '住房', label: '住房', icon: '🏠' },
  { value: '其他', label: '其他', icon: '📦' }
]

// 编辑模式
const isEditMode = ref(false)
const editBillId = ref(null)

// 表单数据
const billForm = ref({
  amount: '',
  purpose: '',
  category: '餐饮',
  billDate: new Date().toISOString().split('T')[0],
  images: []
})

// 文件列表
const fileList = ref([])

// 加载状态
const loading = ref(false)

// 表单引用
const billFormRef = ref(null)

// 表单验证规则
const billRules = {
  amount: [
    { required: true, message: '请输入金额', trigger: 'blur' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的金额格式', trigger: 'blur' },
    {
      validator: (_rule, value, callback) => {
        if (Number(value) <= 0) {
          callback(new Error('金额必须大于0'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  purpose: [
    { required: true, message: '请输入用途说明', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  billDate: [
    { required: true, message: '请选择账单日期', trigger: 'change' }
  ]
}

// 计算是否需要审批
const needApproval = computed(() => {
  return billForm.value.amount && Number(billForm.value.amount) > 100
})

// 上传地址
const uploadAction = computed(() => {
  return import.meta.env.VITE_API_BASE_URL + '/api/upload/bill-image'
})

// 上传请求头
const uploadHeaders = computed(() => {
  const token = localStorage.getItem('token')
  return {
    'Authorization': `Bearer ${token}`
  }
})

// 禁用未来日期
const disabledDate = (time) => {
  return time.getTime() > Date.now()
}

// 上传前验证
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('图片大小不能超过 10MB！')
    return false
  }
  return true
}

// 上传成功回调
const handleUploadSuccess = (response, file, fileList) => {
  if (response.code === 200) {
    billForm.value.images.push(response.data)
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(response.msg || '上传失败')
    // 移除失败的文件
    const index = fileList.findIndex(f => f.uid === file.uid)
    if (index > -1) {
      fileList.splice(index, 1)
    }
  }
}

// 上传失败回调
const handleUploadError = (error) => {
  ElMessage.error('上传失败：' + error.message)
}

// 提交账单
const submitBill = async () => {
  await billFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const billData = {
          amount: Number(billForm.value.amount),
          purpose: billForm.value.purpose,
          category: billForm.value.category,
          billDate: billForm.value.billDate,
          images: billForm.value.images || []
        }

        let res
        if (isEditMode.value) {
          // 编辑模式：更新账单
          res = await updateBill(editBillId.value, billData)
        } else {
          // 创建模式：新建账单
          res = await createBill(billData)
        }

        if (res.code === 200) {
          if (isEditMode.value) {
            ElMessage.success('账单更新成功')
          } else {
            if (needApproval.value) {
              ElMessage.success('账单已提交，等待对方审批')
            } else {
              ElMessage.success('记账成功')
            }
          }
          router.push('/bill/list')
        }
      } catch (error) {
        ElMessage.error(error.response?.data?.msg || (isEditMode.value ? '更新失败' : '提交失败'))
      } finally {
        loading.value = false
      }
    }
  })
}

// 加载账单详情（编辑模式）
const loadBillDetail = async (billId) => {
  try {
    const res = await getBillDetail(billId)
    if (res.code === 200) {
      const bill = res.data

      // 解析 images 字段（JSON 字符串）
      let imagesList = []
      if (bill.images) {
        try {
          imagesList = JSON.parse(bill.images)
        } catch (e) {
          console.error('解析图片列表失败', e)
          imagesList = []
        }
      }

      billForm.value = {
        amount: bill.amount,
        purpose: bill.purpose,
        category: bill.category,
        billDate: bill.billDate,
        images: imagesList
      }

      // 设置文件列表（用于显示已上传的图片）
      if (imagesList.length > 0) {
        fileList.value = imagesList.map((url, index) => ({
          uid: index,
          name: `screenshot-${index}`,
          url: import.meta.env.VITE_API_BASE_URL + url,
          status: 'success'
        }))
      }
    }
  } catch (error) {
    ElMessage.error('加载账单详情失败')
    router.back()
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

onMounted(() => {
  // 检查是否是编辑模式
  const billId = route.query.id
  const edit = route.query.edit

  if (billId && edit === 'true') {
    isEditMode.value = true
    editBillId.value = billId
    loadBillDetail(billId)
  }
})
</script>

<style scoped>
.create-bill-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #ffeef8 0%, #fff5f7 100%);
  padding: 16px;
  padding-bottom: 80px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 22px;
  font-weight: bold;
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.back-btn {
  background: white;
  border: none;
  box-shadow: 0 2px 12px rgba(255, 154, 158, 0.2);
}

.bill-form {
  background: white;
  border-radius: 20px;
  padding: 20px;
  box-shadow: 0 4px 20px rgba(255, 154, 158, 0.15);
}

/* 表单项通用样式 */
.bill-form :deep(.el-form-item) {
  margin-bottom: 24px;
}

.bill-form :deep(.el-form-item__label) {
  padding: 0;
  margin-bottom: 10px;
  line-height: 1.5;
}

.form-label {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 15px;
  font-weight: 600;
  color: #333;
}

.label-icon {
  font-size: 18px;
}

.label-text {
  color: #333;
}

.label-optional {
  font-size: 13px;
  color: #999;
  font-weight: normal;
  margin-left: 4px;
}

/* 金额输入框 */
.form-item-amount :deep(.el-input__wrapper) {
  padding: 12px 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(255, 154, 158, 0.1);
}

.amount-input :deep(.el-input__inner) {
  font-size: 28px;
  font-weight: bold;
  color: #ff9a9e;
  text-align: left;
}

.amount-input :deep(.el-input__prefix) {
  font-size: 24px;
  color: #ff9a9e;
  font-weight: bold;
}

.approval-tip {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 10px;
  padding: 10px 14px;
  background: linear-gradient(135deg, #fff3e0 0%, #ffe8cc 100%);
  border-radius: 10px;
  color: #ff9800;
  font-size: 13px;
  border-left: 3px solid #ff9800;
}

/* 用途说明输入框 */
.form-item-purpose :deep(.el-input__wrapper) {
  padding: 10px 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(255, 154, 158, 0.1);
}

.form-item-purpose :deep(.el-input__inner) {
  font-size: 15px;
}

/* 分类网格 */
.category-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
  width: 100%;
  padding: 4px 0;
}

.category-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 12px 8px;
  background: #fafafa;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
  border: 2px solid transparent;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.04);
  min-height: 75px;
  position: relative;
}

.category-item:active {
  transform: scale(0.95);
}

.category-item.active {
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
  border-color: #ff9a9e;
  color: white;
  box-shadow: 0 4px 12px rgba(255, 154, 158, 0.35);
}

.category-icon {
  font-size: 30px;
  margin-bottom: 4px;
  transition: transform 0.25s ease;
  display: block;
}

.category-item.active .category-icon {
  transform: scale(1.1);
}

.category-label {
  font-size: 12px;
  font-weight: 500;
  text-align: center;
  line-height: 1.3;
  color: #666;
}

.category-item.active .category-label {
  color: white;
  font-weight: 600;
}

/* 日期选择器 */
.form-item-date :deep(.el-input__wrapper) {
  padding: 10px 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(255, 154, 158, 0.1);
}

.form-item-date :deep(.el-input__inner) {
  font-size: 15px;
}

/* 上传区域 */
.upload-section {
  width: 100%;
}

.upload-section :deep(.el-upload-list--picture-card) {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.upload-section :deep(.el-upload--picture-card) {
  width: 80px;
  height: 80px;
  border-radius: 10px;
  border: 2px dashed #ddd;
  background: #fafafa;
  transition: all 0.3s ease;
}

.upload-section :deep(.el-upload--picture-card:hover) {
  border-color: #ff9a9e;
  background: #fff5f7;
}

.upload-section :deep(.el-upload-list__item) {
  width: 80px;
  height: 80px;
  border-radius: 10px;
}

.upload-icon {
  font-size: 24px;
  color: #999;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 6px;
  line-height: 1.4;
}

/* 提交按钮 */
.form-item-submit {
  margin-top: 32px;
  margin-bottom: 0;
}

.submit-btn {
  width: 100%;
  height: 50px;
  font-size: 17px;
  font-weight: bold;
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
  border: none;
  border-radius: 25px;
  box-shadow: 0 4px 15px rgba(255, 154, 158, 0.3);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(255, 154, 158, 0.4);
}

.submit-btn:active {
  transform: translateY(0);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .create-bill-container {
    padding: 12px;
    padding-bottom: 70px;
  }

  .page-header {
    margin-bottom: 16px;
  }

  .page-header h1 {
    font-size: 20px;
  }

  .bill-form {
    padding: 18px;
    border-radius: 18px;
  }

  .bill-form :deep(.el-form-item) {
    margin-bottom: 20px;
  }

  .form-label {
    font-size: 14px;
  }

  .label-icon {
    font-size: 16px;
  }

  .amount-input :deep(.el-input__inner) {
    font-size: 24px;
  }

  .amount-input :deep(.el-input__prefix) {
    font-size: 20px;
  }

  .category-grid {
    gap: 8px;
  }

  .category-item {
    padding: 10px 6px;
    min-height: 70px;
    border-radius: 10px;
  }

  .category-icon {
    font-size: 26px;
    margin-bottom: 3px;
  }

  .category-label {
    font-size: 11px;
  }

  .upload-section :deep(.el-upload--picture-card),
  .upload-section :deep(.el-upload-list__item) {
    width: 70px;
    height: 70px;
  }

  .submit-btn {
    height: 48px;
    font-size: 16px;
  }
}

@media (max-width: 480px) {
  .create-bill-container {
    padding: 10px;
  }

  .bill-form {
    padding: 16px;
  }

  .category-grid {
    gap: 6px;
  }

  .category-item {
    padding: 8px 4px;
    min-height: 65px;
  }

  .category-icon {
    font-size: 24px;
  }

  .category-label {
    font-size: 10px;
  }
}

/* 修复 Element Plus 样式 */
.bill-form :deep(.el-form-item__error) {
  font-size: 12px;
  padding-top: 4px;
}

.bill-form :deep(.el-input__wrapper) {
  transition: all 0.3s ease;
}

.bill-form :deep(.el-input__wrapper:hover) {
  box-shadow: 0 2px 12px rgba(255, 154, 158, 0.15);
}

.bill-form :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 2px 12px rgba(255, 154, 158, 0.25);
}
</style>

